<template>
  <div class="centermap">
    <div class="mapwrap">
      <!-- 移除dv-border-box-13，避免双重边框 -->
      <!-- 加载遮罩 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner" />
        <div class="loading-text">地图加载中...</div>
      </div>

      <!-- 鼠标位置显示 -->
      <div v-if="mousePosition.longitude && mousePosition.latitude" class="mouse-position">经度: {{ formatLng(mousePosition.longitude) }}, 纬度: {{ formatLat(mousePosition.latitude) }}</div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button size="small" type="primary" @click="onClickRefreshBtn">刷新</el-button>
      </div>

      <!-- Cesium 地图容器 -->
      <div id="cesiumContainer" class="map-container" />

      <!-- 雷达信息对话框 -->
      <el-dialog title="雷达信息" :visible.sync="radarDialogVisible" width="400px">
        <div v-if="selectedRadarInfo">
          <p><strong>雷达名称:</strong> {{ selectedRadarInfo.name }}</p>
          <p><strong>位置:</strong> {{ selectedRadarInfo.position }}</p>
          <p><strong>状态:</strong> {{ selectedRadarInfo.status }}</p>
        </div>
      </el-dialog>

      <!-- 监测点信息对话框 -->
      <el-dialog title="监测点信息" :visible.sync="pointDialogVisible" width="400px">
        <div v-if="selectedPointInfo">
          <p><strong>监测点名称:</strong> {{ selectedPointInfo.name }}</p>
          <p><strong>位置:</strong> {{ selectedPointInfo.position }}</p>
          <p><strong>数据:</strong> {{ selectedPointInfo.data }}</p>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { RadarPointTag, RadarTag, TCesiem } from "@/utils/tcesium/tcesium";
import { getRadarPointList } from "@/api/radar/radar-point";
import { getRadarList } from "@/api/radar/sys-radar";

// 引用public下面的Cesium.js
const Cesium = window["Cesium"];

export default {
  data() {
    return {
      loading: true,
      viewer: null,
      handler: null,
      mousePosition: {
        longitude: 0,
        latitude: 0
      },
      radarList: [],
      radarNames: [],
      selectedRadar: "",
      radarDialogVisible: false,
      pointDialogVisible: false,
      selectedRadarInfo: null,
      selectedPointInfo: null,
      radarPointList: [],
      radarRow: null,
      clickRadarRow: null,
      clickRadarPointRow: null,
      openRadarItemDialog: false,
      openRedarPointDetailDialog: false
    };
  },
  computed: {
    selectPointKey() {
      console.log(this.$store.state["xing-bian-screen-setting"].selectPointKey, 'this.$store.state["xing-bian-screen-setting"].selectPointKey');
      return this.$store.state["xing-bian-screen-setting"].selectPointKey;
    }
  },
  watch: {
    selectPointKey: {
      handler(list) {
        this.viewer.entities.values.forEach(item => {
          if (item.id.includes("point")) {
            item.billboard.image._value = "/images/radar/radar_point1.1.png";
            item.billboard.scale = item.billboard.scale._value;
          }
        });
        if (list.length) {
          this.viewer.entities.values.forEach(item => {
            let pointInfo = item.id.split("-");
            let pointKey = pointInfo[2];
            if (list.indexOf(Number(pointKey)) > -1) {
              item.billboard.image._value = "/images/radar/high.png";
            }
            item.billboard.scale = item.billboard.scale._value;
          });
        }
      },
      immediate: true
    }
  },

  created() {
    this.init();
  },

  beforeDestroy() {
    this.viewDestroy();
  },
  methods: {
    async init() {
      try {
        this.loading = true;
        console.log("初始化地图信息");

        // 获取雷达列表
        let resp = await getRadarList();
        let { list } = resp.data;
        console.log("雷达列表：", list);
        this.radarList = list;

        if (!list || list.length === 0) {
          this.loading = false;
          console.error("没有雷达，暂时不显示地图信息！！！");
          return;
        }

        let { lng, lat, radarId } = list[0];
        let pos = { x: lng, y: lat };

        // 创建 Cesium viewer
        this.viewer = await TCesiem.NewTCesium(document.getElementById("cesiumContainer"), pos);
        this.loading = false;

        // 绑定鼠标事件
        this.onCesiumEventHandler();

        // 初始化雷达下拉框
        this.initRadarNames(list);

        // 添加窗口大小变化事件监听器
        window.addEventListener("resize", this.handleResize);

        // 显示雷达实体
        await this.showRadarEntities(radarId);
      } catch (error) {
        console.error("地图初始化失败:", error);
        this.loading = false;
      }
    },

    viewDestroy() {
      console.log("销毁 Cesium 实例及事件监听器");
      if (this.handler && !this.handler.isDestroyed()) {
        this.handler.destroy();
        this.handler = null;
      }
      if (this.viewer && !this.viewer.isDestroyed()) {
        this.viewer.entities.removeAll();
        this.viewer.destroy();
        this.viewer = null;
      }

      // 移除窗口大小监听
      window.removeEventListener("resize", this.handleResize);
    },

    handleResize() {
      if (this.viewer) {
        this.viewer.resize();
      }
    },

    onCesiumEventHandler() {
      if (!this.viewer) return;

      try {
        this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);

        // 鼠标移动事件
        TCesiem.OnMouseMoveEvent(this.viewer, this.handler, position => {
          this.mousePosition.longitude = position.x;
          this.mousePosition.latitude = position.y;
        });

        // 鼠标左键点击事件
        TCesiem.OnMouseLifeClickEvent(this.viewer, this.handler, window.scale, callback => {
          console.log("点击实物:", callback);
          let { id, tag, pos } = callback;

          TCesiem.FlyToPos(this.viewer, 0.5, pos, () => {
            if (tag === RadarTag) {
              this.clickRadarRow = this.radarList.find(item => item.radarKey === id);
              this.selectedRadarInfo = {
                name: this.clickRadarRow?.radarName || this.clickRadarRow?.radarKey,
                position: `${this.clickRadarRow?.lng}, ${this.clickRadarRow?.lat}`,
                status: this.clickRadarRow?.status || "正常"
              };
              this.radarDialogVisible = true;
            }
            if (tag === RadarPointTag) {
              const [radarId, pointKey] = id.split("-");
              this.clickRadarPointRow = this.radarPointList.find(item => item.radarId === radarId);
              // this.clickRadarPointRow = this.radarPointList.find(item => item.pointKey === id);
              this.selectedPointInfo = {
                name: this.clickRadarPointRow?.pointName || this.clickRadarPointRow?.pointKey,
                position: `${this.clickRadarPointRow?.lng}, ${this.clickRadarPointRow?.lat}`,
                data: this.clickRadarPointRow?.data || "暂无数据"
              };
              this.pointDialogVisible = true;
            }
          });
        });
      } catch (error) {
        console.error("绑定鼠标事件失败:", error);
      }
    },

    async showRadarEntities(radarId) {
      if (!this.viewer) return;

      try {
        // 先清空所有实体
        this.viewer.entities.removeAll();

        let radarItem = this.radarList.find(item => item.radarId === radarId);
        this.radarRow = radarItem;
        let { lng, lat, radarKey, radarName } = radarItem;
        let pos = { x: lng, y: lat };

        // 添加雷达
        TCesiem.AddRadarEntities(this.viewer, pos, radarKey, radarName);
        // 飞到指定位置
        TCesiem.FlyToPos(this.viewer, 2, pos, () => {});

        // 添加雷达点位
        let resp = await getRadarPointList({ radarId });
        let radarPointList = resp.data.list;
        this.radarPointList = radarPointList;
        console.log("点位列表：", radarPointList);

        if (!this.viewer || radarPointList.length == 0 || radarPointList[0].radarId != radarId) return;

        for (const item of radarPointList) {
          let { lng, lat, pointKey, pointName } = item;
          console.log(item, "itemitemitemitemitemitem");
          let pos = { x: lng, y: lat };
          console.log(item, "itemitemitemitem");
          TCesiem.AddRadarPointEntities(this.viewer, pos, pointKey, radarId, pointName);
        }
      } catch (error) {
        console.error("显示雷达实体失败:", error);
      }
    },

    initRadarNames(radarList) {
      this.radarNames = [{ label: "全部雷达", value: "" }];
      for (const item of radarList) {
        let { radarKey, radarId } = item;
        this.radarNames.push({ value: radarId, label: radarKey });
      }
      if (this.radarNames.length > 1) {
        this.selectedRadar = this.radarNames[1].value;
      }
    },

    async onClickRefreshBtn() {
      console.log("点击刷新按钮");
      this.viewDestroy();
      await this.init();
    },

    onChangeEvent(value) {
      if (value === "") {
        // 显示所有雷达
        this.showAllRadars();
      } else {
        // 显示特定雷达
        this.showRadarEntities(value);
      }
    },

    async showAllRadars() {
      if (!this.viewer) return;

      try {
        // 清除现有实体
        this.viewer.entities.removeAll();

        // 显示所有雷达
        for (const radar of this.radarList) {
          let { lng, lat, radarKey, radarName } = radar;
          let pos = { x: lng, y: lat };
          TCesiem.AddRadarEntities(this.viewer, pos, radarKey, radarName);
        }

        // 飞行到中国视角
        TCesiem.FlyToPos(this.viewer, 2, { x: 104.0, y: 35.0 }, () => {});
      } catch (error) {
        console.error("显示所有雷达失败:", error);
      }
    },

    // 格式化经度显示
    formatLng(lng) {
      const lngNum = parseFloat(lng);
      const lngStr = `${lngNum.toFixed(6)}${lngNum >= 0 ? "°E" : "°W"}`;
      return lngStr;
    },

    // 格式化纬度显示
    formatLat(lat) {
      const latNum = parseFloat(lat);
      const latStr = `${latNum.toFixed(6)}${latNum >= 0 ? "°N" : "°S"}`;
      return latStr;
    },

    // 切换到上一个雷达
    switchToPreviousRadar() {
      if (this.radarList.length === 0) return null;

      const currentIndex = this.radarList.findIndex(radar => radar.radarId === this.selectedRadar);
      let previousIndex;

      if (currentIndex <= 0) {
        // 如果是第一个或未找到，切换到最后一个
        previousIndex = this.radarList.length - 1;
      } else {
        previousIndex = currentIndex - 1;
      }

      const previousRadar = this.radarList[previousIndex];
      this.selectedRadar = previousRadar.radarId;
      this.showRadarEntities(previousRadar.radarId);
      return previousRadar.radarId; // 返回雷达ID
    },

    // 切换到下一个雷达
    switchToNextRadar() {
      if (this.radarList.length === 0) return null;

      const currentIndex = this.radarList.findIndex(radar => radar.radarId === this.selectedRadar);
      let nextIndex;

      if (currentIndex >= this.radarList.length - 1 || currentIndex === -1) {
        // 如果是最后一个或未找到，切换到第一个
        nextIndex = 0;
      } else {
        nextIndex = currentIndex + 1;
      }

      const nextRadar = this.radarList[nextIndex];
      this.selectedRadar = nextRadar.radarId;
      this.showRadarEntities(nextRadar.radarId);
      return nextRadar.radarId; // 返回雷达ID
    }
  }
};
</script>
<style lang="scss" scoped>
.centermap {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%; // 改为100%高度，填满整个容器
  // 移除max-height限制

  .mapwrap {
    height: 100%;
    width: 100%; // 修改mapwrap宽度为98%
    margin: 0 auto; // 居中显示
    box-sizing: border-box;
    position: relative;

    .loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.7);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      z-index: 1000;

      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #00eded;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }

      .loading-text {
        color: #00f7f6;
        margin-top: 10px;
        font-size: 14px;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    }

    .mouse-position {
      position: absolute;
      top: 10px;
      left: 10px;
      background: rgba(0, 0, 0, 0.7);
      color: #00f7f6;
      padding: 5px 10px;
      border-radius: 4px;
      font-size: 12px;
      z-index: 100;
    }

    .toolbar {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 100;
      display: flex;
      align-items: center;
    }

    .map-container {
      // width: 98%; // 修改map-container宽度为98%
      // margin: 0 auto; // 居中显示
      width: 100%;
      height: 100%;
      //  position: relative;
    }
  }
}

// 全局样式，用于 Cesium 容器
:global(#cesiumContainer) {
  // width: 98% !important;
  width: 100% !important;
  height: 100% !important;
  font-family: sans-serif;
  // margin: 0 auto !important; // 居中显示

  .cesium-widget-credits {
    display: none !important;
  }

  .cesium-viewer-bottom {
    display: none !important;
  }
}

// 针对cesium-widget类的样式调整
:global(.cesium-widget) {
  // width: 98% !important;
  width: 100% !important;
  // margin: 0 auto !important; // 居中显示
}
</style>
